package com.xhj.springbootproject.config;

import com.xhj.springbootproject.constant.object.SelfUserDetails;
import com.xhj.springbootproject.dao.BasicUserDao;
import com.xhj.springbootproject.dao.object.BasicUserDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * @author ：Xionghaijun
 * @date ：Created in 2019/9/25 9:18 AM
 * @description： 登录后设置权限和用户信息
 */
@Component
public class SelfUserDetailsService implements UserDetailsService {

    @Autowired
    private BasicUserDao basicUserDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SelfUserDetails userInfo = new SelfUserDetails();
        userInfo.setUsername(username);
        Md5PasswordEncoder md5PasswordEncoder = new Md5PasswordEncoder();
        BasicUserDO basicUserDO = basicUserDao.queryUserInfoByUserName(username);
        String encodePassword = md5PasswordEncoder.encodePassword(basicUserDO.getUserPassword(), username);
        userInfo.setPassword(encodePassword);
        String[] userRoles = basicUserDO.getUserRoles().split(",");
        Set<GrantedAuthority> authoritiesSet = new HashSet<GrantedAuthority>();
        for (String userRole : userRoles) {
            GrantedAuthority authority = new SimpleGrantedAuthority(userRole);
            authoritiesSet.add(authority);
        }
        userInfo.setAuthorities(authoritiesSet);
        return userInfo;
    }
}
